<?php

namespace Modules\AdminPermission\Services;


use Illuminate\Support\Facades\DB;
use Modules\AdminPermission\Models\Package;
use Modules\AdminPermission\Models\PackagePermission;
use Modules\AdminPermission\Models\TenantryPackage;

class PackageService
{
    // 创建数据
    public function store(array $params)
    {
        try {
            DB::beginTransaction();

            $package = Package::query()
                ->create([
                    'name' => $params['name'], // 名字
                    'description' => $params['description'], // 描述
                    'expired_at' => $params['expired_at'] ?? null, // 有效期
                    'status' => $params['status'] ?? 1, // 1 启动，0 禁用
                ]);

            $this->bindPermissions($package->id, $params['permission_ids']);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
        }
    }

    // 更新数据
    public function update($id, $params)
    {
        try {
            DB::beginTransaction();

            Package::query()
                ->where('id', $id)
                ->update([
                    'name' => $params['name'], // 名字
                    'description' => $params['description'], // 描述
                    'expired_at' => $params['expired_at'], // 有效期
                    'status' => $params['status'], // 1 启动，0 禁用
                ]);

            PackagePermission::query()->where('package_id', $id)->delete();
            $permissionIds = $params['permission_ids'] ?? [];
            $this->bindPermissions($id, $permissionIds);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
        }
    }

    // 列表数据
    public function getBuilder(array $params = [])
    {
        return Package::query()
            // 名字
            ->where(function ($query) use ($params) {
                $name = trim($params['name'] ?? '');
                if (strlen($name) > 0) {
                    $query->where('name', 'like', "%{$name}%");
                }
            })
            // 描述
            ->where(function ($query) use ($params) {
                $description = trim($params['description'] ?? '');
                if (strlen($description) > 0) {
                    $query->where('description', 'like', "%{$description}%");
                }
            })
            // 有效期
            ->where(function ($query) use ($params) {
                $startExpiredAt = $params['start_expired_at'] ?? null;
                if ($startExpiredAt) {
                    $query->where('expired_at', '>=', $startExpiredAt);
                }
                $endExpiredAt = $params['end_expired_at'] ?? null;
                if ($endExpiredAt) {
                    $query->where('expired_at', '<=', $endExpiredAt);
                }
            })
            // 状态
            ->where(function ($query) use ($params) {
                $status = trim($params['status'] ?? '');
                if (strlen($status) > 0) {
                    $query->where('status', $status);
                }
            });
    }

    // 删除数据
    public function destroy($id)
    {
        try {
            DB::beginTransaction();

            Package::query()->where('id', $id)->delete();

            PackagePermission::query()->where('package_id', $id)->delete();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
        }
    }

    // 租户绑定套餐
    public function bindPackagesForTenantry(int $tenantryId, $packageIds)
    {
        $data = [];
        $packageIds = collect($packageIds);
        foreach ($packageIds as $packageId) {
            $data[] = [
                'package_id' => $packageId,
                'tenantry_id' => $tenantryId,
            ];
        }
        if (count($data) > 0) {
            TenantryPackage::query()->insert($data);
        }
    }

    protected function bindPermissions(int $packageId, $permissionIds)
    {
        $data = [];
        $permissionIds = collect($permissionIds);
        foreach ($permissionIds as $permissionId) {
            $data[] = [
                'package_id' => $packageId,
                'permission_id' => $permissionId,
            ];
        }
        if (count($data) > 0) {
            PackagePermission::query()->insert($data);
        }
    }

}
